﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlMatHang : System.Web.UI.UserControl
{
    
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (ViewState["flag"] == null)
            {
                //ViewState["flag"] = false;
                ClearAdd();
            }
            //nằm trong thread
           
            ThreadStart thr1=new ThreadStart(LoadNganhHang);
            ThreadStart thr2 = new ThreadStart(LoadVendor);
            //ThreadStart thr3 = new ThreadStart(delegate() {LoadSanPham(Int32.Parse(ddlNganhHang.SelectedValue.ToString())); });
            ThreadStart thr4 = new ThreadStart(loadStatusItemList);
            ThreadStart thr5 = new ThreadStart(LoadVat);

            Thread tr1 = new Thread(thr1);
            Thread tr2 = new Thread(thr2);
            //Thread tr3 = new Thread(thr3);
            Thread tr4 = new Thread(thr4);
            Thread tr5 = new Thread(thr5);

            tr1.Start();
            tr2.Start();
            //tr3.Start();
            tr4.Start();
            tr5.Start();

            tr1.Join();
            try
            {
                LoadNhanHieu(Int32.Parse(ddlNganhHang.SelectedValue.ToString()));
                LoadSanPham(Int32.Parse(ddlNganhHang.SelectedValue.ToString()));
            }
            catch
            {

            }
            tr2.Join();
            //tr3.Join();
            tr4.Join();
            tr5.Join();
            //nằm trong thread
        }
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    void LoadSanPham(Int32 CatID)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getProductList]", CommandType.StoredProcedure,
                new SqlParameter("@Act", 1),
                new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                new SqlParameter("@CatID", CatID));
            dt.BindDropDownList(db, ddlProduct, "MaSanPham", "SanPham");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadNhanHieu(Int32 CatID)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
                new SqlParameter("@Act", 1),
                new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                new SqlParameter("@CatID",CatID));
            dt.BindDropDownList(db, ddlNhanHieu, "MaNhanHieu", "NhanHieu");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadNganhHang()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getCategoryList]", CommandType.StoredProcedure,
                new SqlParameter("@Act",1),
                new SqlParameter("@sitecode",Session["sitecode"].ToString()));
            dt.BindDropDownList(db, ddlNganhHang, "CommodKey", "Description");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadVat()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getVATTypeList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, ddlVAT, "purchasetaxkey", "purchasetaxdesc");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void loadStatusItemList()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getItemStatusList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, ddlStatus, "mVal", "mText");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadVendor()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getVendor]", CommandType.StoredProcedure,
                new SqlParameter("@sitecode",Session["sitecode"].ToString()));
            dt.BindDropDownList(db, ddVendor, "vendorkey", "vendorname");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtMaSo.Focus();
        txtDescription.Text = "";
        txtDescription1.Text = "";
        txtExtendedCode.Text = "";
        txtMaSo.Text = "";
        txtMaSo1.Text = "";
        txtPrice.Text = "";

        txtUnit.Text = "";
        ViewState["flag"] = true;

        btnSave.Text = "Lưu";
        lblMsg.Text = "";
        lblMsg.Visible = false;
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();        
    }
    
    protected void grvMatHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvMatHang.PageIndex = e.NewPageIndex;
        LoadGrid();
    }
    protected void grvMatHang_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl(DRMConstants.CONTROL_NAME_LABEL_MASO);

                DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getDetailItemInfo]", CommandType.StoredProcedure,
                    new SqlParameter("@mastID", lblMaSo.Text));
                txtMaSo.Text = db.Rows[0]["MaHang"].ToString();
                txtDescription.Text = db.Rows[0]["MatHang"].ToString();
                txtMaSo1.Text = db.Rows[0]["MaHang1"].ToString();
                txtDescription1.Text = db.Rows[0]["MatHang1"].ToString();
                txtExtendedCode.Text = db.Rows[0]["MaMoRong"].ToString();
                txtUnit.Text = db.Rows[0]["ConVertDesc"].ToString();

                try
                {
                    ddlVAT.SelectedValue = db.Rows[0]["VAT"].ToString();
                }
                catch
                {
                }
                try
                {
                    ddlNganhHang.SelectedValue = db.Rows[0]["MaNganhHang"].ToString();
                    LoadNhanHieu(Int32.Parse(ddlNganhHang.SelectedValue.ToString()));
                    LoadSanPham(Int32.Parse(ddlNganhHang.SelectedValue.ToString()));
                }
                catch
                {
                }
                try
                {
                    ddlNhanHieu.SelectedValue = db.Rows[0]["MaNhanHieu"].ToString();
                }
                catch
                {
                }
                try
                {
                    ddlProduct.SelectedValue = db.Rows[0]["MaSanPham"].ToString();
                }
                catch
                {
                }
                txtPrice.Text = db.Rows[0]["Gia"].ToString();
               
                try
                {
                    ddlStatus.SelectedValue = db.Rows[0]["TrangThai"].ToString();
                }
                catch
                {
                }
                try
                {
                    ddVendor.SelectedValue = db.Rows[0]["vendorkey"].ToString();
                }
                catch
                {
                }

                lblMsg.Text = "";
                lblMsg.Visible = false;
                btnSave.Text = "Cập nhật";

                grvMatHang.DataSource = null;
                grvMatHang.DataBind();

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        LoadGrid();
    } 
    private void LoadGrid()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error,"ls_searchItem", CommandType.StoredProcedure,
                new SqlParameter("@content", txtSearch.Text),
                new SqlParameter("@sitecode",Session["sitecode"].ToString()));


            if (db.Rows.Count > 0)
            {
                grvMatHang.DataSource = db;

            }
            else
            {
                grvMatHang.DataSource = null;
                ShowMessageBox("Không tìm thấy kết quả");
             
            }
            grvMatHang.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void ddlNganhHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ThreadStart thr2 = new ThreadStart(delegate() { LoadNhanHieu(Int32.Parse(ddlNganhHang.SelectedValue.ToString())); });
            ThreadStart thr3 = new ThreadStart(delegate() { LoadSanPham(Int32.Parse(ddlNganhHang.SelectedValue.ToString())); });

            Thread tr2 = new Thread(thr2);
            Thread tr3 = new Thread(thr3);

            tr2.Start();
            tr3.Start();

            tr2.Join();
            tr3.Join();
        }
        catch
        {

        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        int i = 1;
        if (txtPrice.Text == "")
        {
            txtPrice.Text = "0";
        }

        try
        {
            if ((bool)ViewState["flag"])
            {
                //insert
                i = dt.ExecuteSQl_int(str, "ls_saveInmastInfo", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@mastID", txtMaSo.Text.Trim()),
                            new SqlParameter("@description", txtDescription.Text),
                            new SqlParameter("@mastID1", txtMaSo1.Text.Trim()),
                            new SqlParameter("@description1", txtDescription1.Text),
                            new SqlParameter("@barCode", txtExtendedCode.Text.Trim()),
                            new SqlParameter("@cvrtDesc", txtUnit.Text),
                            new SqlParameter("@VATRate", ddlVAT.SelectedValue),
                            new SqlParameter("@categoryID", ddlNganhHang.SelectedValue.ToString()),
                            new SqlParameter("@brandID", ddlNhanHieu.SelectedValue.ToString()),
                            new SqlParameter("@productID", ddlProduct.SelectedValue.ToString()),
                            new SqlParameter("@vendorkey", ddVendor.SelectedValue.ToString()),
                            new SqlParameter("@price", float.Parse(txtPrice.Text)),
                            new SqlParameter("@status", ddlStatus.SelectedValue),
                            new SqlParameter("@isAddNew", 2),
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                if (i == 2)
                {
                    //ShowMessageBox("Thêm mặt hàng mới thành công");
                    ClearAdd();
                    lblMsg.Text = "Thêm mặt hàng mới thành công";
                    lblMsg.Visible = true;
                }
                else if (i == 3)
                {
                    //ShowMessageBox("Mã hàng 1 bị trùng,đề nghị nhập mã khác");
                    lblMsg.Text = "Mã hàng 1 bị trùng,đề nghị nhập mã khác";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;
                }

                //ViewState["flag"] = false;


                //txtDescription.Text = "";
                //txtDescription1.Text = "";
                //txtExtendedCode.Text = "";
                //txtMaSo.Text = "";
                //txtMaSo1.Text = "";
                //txtPrice.Text = "";

                //txtUnit.Text = "";

            }
            else
            {
                //update
                i = dt.ExecuteSQl_int(str, "ls_saveInmastInfo", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@mastID", txtMaSo.Text.Trim()),
                            new SqlParameter("@description", txtDescription.Text),
                            new SqlParameter("@mastID1", txtMaSo1.Text.Trim()),
                            new SqlParameter("@description1", txtDescription1.Text),
                            new SqlParameter("@barCode", txtExtendedCode.Text.Trim()),
                            new SqlParameter("@cvrtDesc", txtUnit.Text),
                            new SqlParameter("@VATRate", ddlVAT.SelectedValue),
                            new SqlParameter("@categoryID", ddlNganhHang.SelectedValue),
                            new SqlParameter("@brandID", ddlNhanHieu.SelectedValue),
                            new SqlParameter("@productID", ddlProduct.SelectedValue),
                            new SqlParameter("@vendorkey", ddVendor.SelectedValue.ToString()),
                            new SqlParameter("@price", float.Parse(txtPrice.Text)),
                            new SqlParameter("@status", ddlStatus.SelectedValue),
                            new SqlParameter("@isAddNew", 1),
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                if (i == 2)
                {
                    //ShowMessageBox("Cập nhật mặt hàng thành công");
                    lblMsg.Text = "Cập nhật mặt hàng thành công";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;

                }
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
}